<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems as Emslib;
use app\common\model\User;

/**
 * Openid接口
 */
class Openid extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取openid
     *
     * @param string $email 邮箱
     * @param string $event 事件名称
     */
    public function index()
    {
        $code = $this->request->request("code");
        
        if(empty($code)){
            $this->error("code不能为空");
        }

        $appid = config("wxpay.appid");
        $appSecret = config("wxpay.appSecret");
        $wxUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

        $getUrl = sprintf($wxUrl,$appid,$appSecret,$code);
        //请求url
        $result = $this->curl_get_https($getUrl);
        $wxResult = json_decode($result,true);

       // var_dump($wxResult);

        if(empty($wxResult)){
            $this->error("获取openid时异常，微信内部错误");
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);

            if($loginFail){
                $this->error("获取openid时失败");
            }else{
                $openid = $wxResult['openid'];
                $this->success(__('获取成功'),$openid);
            }
        }
    }

    /**
     * 模拟get进行url请求
     * @param string $url
     * @param string $param
     */
    public function  curl_get_https($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }


}
